package com.ch03.file;

import java.sql.*;
import java.util.*;

public class StockDBWriter {

	public void updateDB(ArrayList lines) throws Exception
	{
		//String url = "jdbc:oracle:thin:@12.195.10.254:1521:orcl";
		String url = "jdbc:mysql://localhost/stockapp";
		String username = "root";
		String password = "admin001";
		
		try {
			System.out.println("Trying to update db");
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(url, username, password);
			
			Statement s = con.createStatement();
			/* String selectSql = "Select * from stock where stock_code like '" + stockData[0] + "'";
			 ResultSet rs = s.executeQuery(selectSql);
			if ( rs != null)
			{
				throw new SQLException("Duplicate keys");
			} */
			for (Iterator iter = lines.iterator(); iter.hasNext();) {
				String line = (String) iter.next();
				String[] stockData = line.split(",");
				String sql = "INSERT INTO stock VALUES ('" + stockData[0] + "', '" + stockData[1] + "');";
				try {
					s.execute(sql);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
			}
			
			s.close();
			con.close();
		}
		catch (Exception exception) {
			 throw new Exception (exception.getMessage());
		}
	}
}
